<?php

namespace app\common\model\mycurrency;

use think\Model;
use traits\model\SoftDelete;

class MerchantMoneyLog extends Model
{

    //use SoftDelete;

    

    // 表名
    protected $name = 'mycurrency_merchant_money_log';

    const CHANGE_TYPE_MERCHANT = 1;//变动身份 商铺余额变动
    const CHANGE_TYPE_STORE = 2;//变动身份 门店余额变动


    const TYPE_HOUTAITIANJIA = 1;//余额变动类型 -后台添加
    const TYPE_HOUTAIJIANSHAO = 2;//余额变动类型 -后台减少
    const TYPE_YONGHUXIAOFEI = 3;//余额变动类型 - 用户消费收益
    const TYPE_TIXIAN = 4;//余额变动类型 - 商铺提现
    const TYPE_TIXIANBOHUI = 5;//余额变动类型 - 商铺提现驳回


    /**
     * 处理商铺或门店余额变动
     * @param int $change_type 变动身份:1=商铺余额变动,2=门店余额变动
     * @param int $merchant_id 商铺ID
     * @param int $store_id 门店ID
     * @param int $money 变动金额
     * @param  int $type 变动类型
     * @param array $data 数据
     */
    public static function moneyChange($change_type,$merchant_id,$store_id,$money,$type,$data=[])
    {
        if($change_type == self::CHANGE_TYPE_MERCHANT){//商铺余额变动
            $merchant = Merchant::get($merchant_id);
        }elseif($change_type == self::CHANGE_TYPE_STORE){//门店余额变动
            $merchant = MerchantStore::get($store_id);
        }
        $before = $merchant['money'];//变更前余额
        $after = 0;//变更后余额
        if($type == self::TYPE_HOUTAITIANJIA || $type == self::TYPE_YONGHUXIAOFEI || $type == self::TYPE_TIXIANBOHUI){//后台添加  用户消费收益  提现驳回
            $after = $before + $money;
        }elseif ($type == self::TYPE_HOUTAIJIANSHAO || $type == self::TYPE_TIXIAN){
            $after = $before - $money;
        }
        $merchant->money = $after;
        $merchant->save();

        $insertData = [
            'change_type' => $change_type,
            'money' => $money,
            'before' => $before,
            'after' => $after,
            //'memo' => '',
            'createtime' => time(),
            'type' => $type
        ];
        if($change_type == self::CHANGE_TYPE_MERCHANT){//商铺余额变动
            $insertData['merchant_id'] = $merchant_id;
        }elseif($change_type == self::CHANGE_TYPE_STORE){//门店余额变动
            $insertData['store_id'] = $store_id;
        }
        $data = array_merge($insertData,$data);
        self::create($data);
    }


}
